package com.david.service.Impl;

import cn.dev33.satoken.stp.StpUtil;
import com.david.dao.AdminUserMapper;
import com.david.entity.AdminUser;
import com.david.entity.LogDetail;
import com.david.entity.LogMessage;
import com.david.entity.RegisterHr;
import com.david.service.UserLoginInterface;
import com.david.vo.CardBean;
import com.david.vo.UserImage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author David
 */
@Service
@Slf4j
public class UserLoginServiceImpl implements UserLoginInterface {

    @Resource
    private AdminUserMapper adminUserMapper;

    @Resource
    private HttpServletResponse response;

    @Resource
    private HttpServletRequest request;

    @Override
    public CardBean adminLogin(AdminUser adminUser){
        String username = adminUser.getUsername();
        String password = adminUser.getPassword();

        CardBean baseBean = new CardBean();

        // 前期防呆设计，后期记录登陆的账户及其状态
        if("".equals(username)){
            baseBean.setMsg("账 号 不 能 为 空");
            baseBean.setCode(1);
        }else if("".equals(password)){
            baseBean.setMsg("密 码 不 能 为 空");
            baseBean.setCode(1);
        }else{
            if(adminUserMapper.adminLogin(username) == null){
                baseBean.setMsg("有 账 号 吗 你 就 登？");
                baseBean.setCode(1);
                log.warn("【登陆失败】用户{}不存在", username);
            }else if(!adminUserMapper.adminLogin(username).getPassword().equals(password)){
                baseBean.setCode(1);
                baseBean.setMsg("密 码 忘 了？兄 弟");
                log.warn("【登陆失败】密码错误，输入用户名为：" + username + "输入密码为：" + password);
            }else{
                baseBean.setMsg("登 录 成 功");
                baseBean.setCode(0);
                log.info("【登陆成功】用户名为：{}", username);
            }
        }

        // 如果验证成功，则给客户端发一个cookie，用来标识请求者的身份，如果用户选择了记住密码，则再发送一个密码
        if(baseBean.getCode() == 0){
            Cookie cookie = new Cookie("username", username);
            // 设置cookie存在七天，按秒为单位
            cookie.setMaxAge(60*60*24*7);
            cookie.setPath("/");
            response.addCookie(cookie);
            if ("on".equals(adminUser.getRemember())){
                Cookie cookie1 = new Cookie("password", password);
                // 设置cookie存在七天，按秒为单位
                cookie1.setMaxAge(60*60*24*7);
                cookie1.setPath("/");
                response.addCookie(cookie1);
            }

            // 登陆成功，判断之前没登陆过，这儿使用session来进行计数
            HttpSession session = request.getSession();
            session.setAttribute("username", username);

            LogMessage logMessage = adminUserMapper.findAdmin(username);
            // 添加主页显示的log
            adminUserMapper.addLog(logMessage);

            // 集成sa-token，使用名字来生成token，发放令牌
            StpUtil.setLoginId(username);
        }

        // 添加登录日志的log，无论是否登陆成功，均记录下来
        LogDetail logDetail = new LogDetail();
        // 获取消息
        logDetail.setInfo(baseBean.getMsg());
        // 获取操作系统信息
        String head = request.getHeader("User-Agent");
        String userAgent = head.toLowerCase();
        String os = "";
        if (userAgent.contains("windows"))
        {
            os = "Windows";
        } else if(userAgent.contains("mac"))
        {
            os = "Mac";
        } else if(userAgent.contains("x11"))
        {
            os = "Unix";
        } else if(userAgent.contains("android"))
        {
            os = "Android";
        } else if(userAgent.contains("iphone"))
        {
            os = "IPhone";
        }else{
            os = "UnKnown, More-Info: " + userAgent;
        }
        logDetail.setSystemOs(os);
        // 输入浏览器信息
        if (userAgent.contains("edg"))
        {
            logDetail.setBrowser("Edge浏览器");
        } else if (userAgent.contains("chrome"))
        {
            logDetail.setBrowser("谷歌浏览器");
        } else if ( userAgent.contains("opr") || userAgent.contains("opera"))
        {
            logDetail.setBrowser("Oprea浏览器");
        } else if (userAgent.contains("safari"))
        {
            logDetail.setBrowser("Safari浏览器");
        } else if (userAgent.contains("firefox"))
        {
            logDetail.setBrowser("火狐浏览器");
        } else if(userAgent.contains("rv"))
        {
            logDetail.setBrowser("IE浏览器");
        } else
        {
            logDetail.setBrowser("未知浏览器");
        }
        // 获取请求者的地址，不用nginx就换成此注释代码
//        logDetail.setOperateAddress(request.getRemoteAddr());
        logDetail.setOperateAddress(request.getHeader("X-Real-IP"));
        if(logDetail.getOperateAddress() == null){
            logDetail.setOperateAddress(request.getRemoteAddr());
        }
        // 获取请求的完整url
        logDetail.setOperateUrl(request.getRequestURL().toString());
        // 获取请求机的端口号
        logDetail.setPort(String.valueOf(request.getRemotePort()));
        // 获取请求机的系统型号

        // 获取此请求是否成功
        if(baseBean.getCode() == 0){
            logDetail.setSuccess("true");
        }else {
            logDetail.setSuccess("false");
        }
        // 获取请求者的账号名称
        logDetail.setOperateName(username);
        // 数据库中保存数据
        adminUserMapper.saveLogDetail(logDetail);
        return baseBean;
    }

    @Override
    public CardBean saveHr(RegisterHr message){
        CardBean baseBean = new CardBean();
        if (adminUserMapper.findAdmin(message.getUsername()) != null){
            baseBean.setMsg("账户已存在！");
            baseBean.setCode(1);
        }else{
            if ("".equals(message.getFile())){
                message.setFile("../../admin/images/88.jpg");
            }else{
                String file = message.getFile().substring(12);
                String filePath = "../../admin/images/";
                message.setFile(filePath + file);
            }
            adminUserMapper.saveHr(message);

            baseBean.setMsg("注册成功！");
            baseBean.setCode(0);
        }
        return baseBean;
    }

    @Override
    public CardBean loginInit(){
        CardBean userImage = new CardBean();

        userImage.setMsg(request.getSession(false).getAttribute("username").toString());
        userImage.setCode(0);

        return userImage;
    }
}
